﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using YY.UI.BaseDataSvc;
using System.Linq;
using YY.Common;

namespace YY.UI
{
    public partial class EditBalanceFrm : BaseFrm
    {
        /// <summary>
        /// 编辑模式时传入id
        /// </summary>
        public int Id { get; set; }

        /// <summary>
        /// 新增调用设定为 true, 编辑调用设定为 false
        /// </summary>
        public bool EditMode { get; set; }

        public EnumCommon.FeeType BalanceType { get; set; }

        IEnumerable<TB_Clients> clients = null;
        IEnumerable<TB_Options> options = null;
        public EditBalanceFrm()
        {
            InitializeComponent();
            this.BaseDataProxy = new BaseDataSvc.BaseDataClient();
            this.cbBoxTarget.KeyPress += new KeyPressEventHandler(cbBoxTarget_KeyPress);
        }

        private void EditBalanceFrm_Load(object sender, EventArgs e)
        {
            this.BaseDataProxy.Open();
            init();
        }

        void init()
        {
            if (!Enum.IsDefined(typeof(EnumCommon.FeeType), this.BalanceType))
                this.BalanceType = EnumCommon.FeeType.应收;
            Common.BindEnumToComboBox(this.cbBoxBalanceType, typeof(EnumCommon.FeeType), this.BalanceType.ToString());

            clients = this.BaseDataProxy.FindClients(null, null, null, null, null);
            this.options = this.BaseDataProxy.FindOptions(EnumCommon.OptionType.结算对象.ToString(), null, null);

            Common.ComboBoxBindDatas<TB_Clients>(this.cbBoxTarget, clients, "fullName", "id");
            if (this.EditMode)
            {
                TB_Balance balance = this.BaseDataProxy.GetBalance(Convert.ToInt32(this.Id));
                this.txtBoxAmount.Text = balance.amount.ToString("0.00");
                this.txtBoxBank.Text = balance.bank;
                this.txtBoxDesc.Text = balance.desc;
                this.txtBoxMemo.Text = balance.memo;
                this.dTPDate.Value = balance.bDate;
                if (balance.target.HasValue)
                {
                    if (balance.bType == (int)EnumCommon.FeeType.应收)
                        this.cbBoxTarget.SelectedItem = this.clients.SingleOrDefault(p => p.id == balance.target.Value);
                    else
                        this.cbBoxTarget.SelectedItem = this.options.SingleOrDefault(p => p.id == balance.target.Value);
                }
            }
        }

        bool inputValidate()
        {
            if (string.IsNullOrEmpty(this.txtBoxAmount.Text))
            {
                MessageBox.Show("请输入金额！");
                this.txtBoxAmount.Focus();
                return false;
            }
            return true;
        }

        void resetNew()
        {
            this.Id = 0;
            this.EditMode = false;
            Common.ResetControl(this, new string[] { this.cbBoxBalanceType.Name.ToString(), this.cbBoxTarget.Name.ToString() });
        }

        void save(Common.SaveMode saveMode)
        {
            bool saveOK = false;
            int currentId = 0;
            Common.OperateType opType = Common.OperateType.Add;
            if (inputValidate())
            {
                TB_Balance blc = new TB_Balance();
                Common.EvalControlValueToData(blc, "amount", this.txtBoxAmount.Text);
                Common.EvalControlValueToData(blc, "bank", this.txtBoxBank.Text);
                Common.EvalControlValueToData(blc, "bDate", this.dTPDate.Value);
                Common.EvalControlValueToData(blc, "bType", this.BalanceType);
                Common.EvalControlValueToData(blc, "desc", this.txtBoxDesc.Text);
                Common.EvalControlValueToData(blc, "memo", this.txtBoxMemo.Text);
                Common.EvalControlValueToData(blc, "target", this.cbBoxTarget.SelectedValue);

                if (this.EditMode)
                {
                    blc.id = this.Id;
                    if (this.BaseDataProxy.UpdateBalance(blc))
                    {
                        opType = Common.OperateType.Update;
                        MessageBox.Show("资料更新完成！");
                        saveOK = true;
                        currentId = blc.id;
                    }
                    else
                        MessageBox.Show("资料更新异常！");
                }
                else
                {
                    currentId = this.BaseDataProxy.AddBalance(blc);
                    if (currentId > 0)
                    {
                        blc.id = currentId;
                        MessageBox.Show("新建完成！");
                        saveOK = true;

                    }
                    else
                        MessageBox.Show("新建异常！");
                }

                if (saveOK)
                {
                    CommonEventArg<TB_Balance> arg = new CommonEventArg<TB_Balance>(blc, opType);
                    EventCommon.OnBalanceUdDGVEvnt(this, arg);

                    if (saveMode == Common.SaveMode.SaveAndNew)
                    {
                        resetNew();
                    }
                    else if (saveMode == Common.SaveMode.SaveAndClose)
                    {
                        this.Close();
                    }
                    else
                    {
                        this.Id = currentId;
                        this.EditMode = true;
                    }
                }
            }
        }

        private void txtBoxAmount_KeyPress(object sender, KeyPressEventArgs e)
        {
            if ((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8 && e.KeyChar != 13 && e.KeyChar != 45 && e.KeyChar != 46)
                e.Handled = true;

            //输入为负号时，只能输入一次且只能输入一次
            if (e.KeyChar == 45 && (((TextBox)sender).SelectionStart != 0 || ((TextBox)sender).Text.IndexOf("-") >= 0))
                e.Handled = true;
            if (e.KeyChar == 46 && ((TextBox)sender).Text.IndexOf(".") >= 0)
                e.Handled = true;
        }

        private void btnNew_Click(object sender, EventArgs e)
        {
            resetNew();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            save(Common.SaveMode.Save);
        }

        private void btnSaveAndNew_Click(object sender, EventArgs e)
        {
            save(Common.SaveMode.SaveAndNew);
        }

        private void btnSaveAndClose_Click(object sender, EventArgs e)
        {
            save(Common.SaveMode.SaveAndClose);
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (this.EditMode)
            {
                if (MessageBox.Show("确认删除该项吗？", "删除提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    if (this.BaseDataProxy.DeleteBalance(this.Id))
                    {
                        MessageBox.Show("删除成功！");
                        this.Close();
                    }
                    else
                        MessageBox.Show("删除失败！");
                }
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        void cbBoxTarget_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
            {
                ComboBox cbBox = sender as ComboBox;
                if (this.clients != null)
                {
                    TB_Clients[] datas = this.clients.Where(p => p.fullName.Contains(cbBox.Text) || p.shortName.Contains(cbBox.Text)).ToArray();
                    Common.ComboBoxMatchClient(cbBox, datas, this);
                }
            }
        }

        void cbBoxTarget_KeyPress2(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
            {
                ComboBox cbBox = sender as ComboBox;
                EnumCommon.OptionType ot = (EnumCommon.OptionType)cbBox.Tag;
                if (this.options != null)
                {
                    TB_Options[] os = this.options.Where(p => p.type == ot.ToString()).Where(p => p.name.Contains(cbBox.Text) || p.code.Contains(cbBox.Text)).ToArray();
                    Common.ComboBoxMatchOption(cbBox, os, this, ot);
                }
            }
        }

        private void cbBoxBalanceType_SelectedIndexChanged(object sender, EventArgs e)
        {
            //bool show = false;
            if (this.cbBoxBalanceType.SelectedItem != null)
            {
                this.BalanceType = (EnumCommon.FeeType)Enum.Parse(typeof(EnumCommon.FeeType), this.cbBoxBalanceType.SelectedItem.ToString());
                //if (this.BalanceType == EnumCommon.FeeType.应收)
                //    show = true;
            }
            //this.label2.Visible = show;
            //this.cbBoxTarget.Visible = show;
        }

        void bindTarget()
        {
            if (this.cbBoxBalanceType.SelectedItem != null)
            {
                this.BalanceType = (EnumCommon.FeeType)Enum.Parse(typeof(EnumCommon.FeeType), this.cbBoxBalanceType.SelectedItem.ToString());
                if (this.BalanceType == EnumCommon.FeeType.应收)
                {
                    Common.ComboBoxBindDatas<TB_Clients>(this.cbBoxTarget, this.clients, "fullName", "id");
                    this.cbBoxTarget.KeyPress -= new KeyPressEventHandler(cbBoxTarget_KeyPress2);
                    this.cbBoxTarget.KeyPress += new KeyPressEventHandler(cbBoxTarget_KeyPress);
                }
                else
                {
                    Common.BindOptionsComboBox(this.cbBoxTarget, this.options, EnumCommon.OptionType.结算对象);
                    this.cbBoxTarget.KeyPress -= new KeyPressEventHandler(cbBoxTarget_KeyPress);
                    this.cbBoxTarget.KeyPress += new KeyPressEventHandler(cbBoxTarget_KeyPress2);
                }
            }
        }
    }
}
